'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Form,
  Input,
  Button,
  Card,
  Typography,
  message,
  Divider,
  Space,
  Alert,
} from 'antd';
import { UserOutlined, LockOutlined, LoginOutlined } from '@ant-design/icons';
import { LoginRequest, LoginResponse } from '@/types/auth';
import { tokenManager, userManager } from '@/utils/auth';

const { Title, Text } = Typography;

const LoginPage: React.FC = () => {
  const router = useRouter();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 检查是否已经登录
  useEffect(() => {
    const token = tokenManager.getToken();
    if (token) {
      // 如果已登录，重定向到首页
      router.replace('/');
    }
  }, [router]);

  const handleLogin = async (values: LoginRequest) => {
    setLoading(true);
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const result: LoginResponse = await response.json();

      if (result.success && result.data) {
        // 保存 token 和用户信息
        tokenManager.setToken(result.data.token);
        userManager.setUser(result.data.user);

        message.success(result.message || '登录成功');
        
        // 重定向到首页
        router.replace('/');
      } else {
        message.error(result.message || '登录失败');
      }
    } catch (error) {
      console.error('登录失败:', error);
      message.error('登录失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleTestLogin = (username: string) => {
    const testCredentials: Record<string, string> = {
      admin: 'admin123',
      manager1: 'manager123',
      dev1: 'dev123',
      guest1: 'guest123',
    };

    form.setFieldsValue({
      username,
      password: testCredentials[username],
    });
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
    }}>
      <Card
        style={{
          width: '100%',
          maxWidth: 400,
          boxShadow: '0 10px 25px rgba(0, 0, 0, 0.1)',
          borderRadius: 12,
        }}
      >
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{
            width: 64,
            height: 64,
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            borderRadius: '50%',
            margin: '0 auto 16px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <LoginOutlined style={{ fontSize: 24, color: 'white' }} />
          </div>
          <Title level={2} style={{ margin: 0, color: '#262626' }}>
            后台管理系统
          </Title>
          <Text type="secondary">请登录您的账户</Text>
        </div>

        <Form
          form={form}
          name="login"
          onFinish={handleLogin}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 2, message: '用户名至少2个字符' },
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              style={{
                height: 44,
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                border: 'none',
                borderRadius: 6,
              }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <Divider>测试账户</Divider>

        <Alert
          message="Demo 测试账户"
          description={
            <div style={{ marginTop: 8 }}>
              <Text style={{ fontSize: 12, color: '#666' }}>
                点击下方按钮快速填充登录信息：
              </Text>
              <div style={{ marginTop: 8 }}>
                <Space wrap>
                  <Button
                    size="small"
                    onClick={() => handleTestLogin('admin')}
                  >
                    管理员
                  </Button>
                  <Button
                    size="small"
                    onClick={() => handleTestLogin('manager1')}
                  >
                    经理
                  </Button>
                  <Button
                    size="small"
                    onClick={() => handleTestLogin('dev1')}
                  >
                    普通用户
                  </Button>
                  <Button
                    size="small"
                    onClick={() => handleTestLogin('guest1')}
                  >
                    访客
                  </Button>
                </Space>
              </div>
            </div>
          }
          type="info"
          showIcon
          style={{ marginBottom: 0 }}
        />
      </Card>
    </div>
  );
};

export default LoginPage; 